﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Common.Library;
using OnlineVideos.Common;
using OnlineVideos.UI;

using OnlineVideos.Entities;
using System.Windows.Navigation;

using OnlineVideos.Library;

using OnlineVideos.View_Models;
using System.ComponentModel;
using OnlineVideos.Data;

using Microsoft.Phone.Controls;
using System.Collections;
using Common;
using Common.Utilities;
using System.Threading.Tasks;
using FlurryWP8SDK.Models;
namespace OnlineVideos
{

    public partial class ShowCast : UserControl
    {
        #region GlobalDeclaration
        private static bool IsDataLoaded;
        List<CastRole> ShowCastList = null;
        #endregion

        #region Constructor
        public ShowCast()
        {
            InitializeComponent();
            ShowCastList = new List<CastRole>();
            IsDataLoaded = false;

        }
        #endregion

        #region PageLoad
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
                if (IsDataLoaded == false)
                {
                    MyProgressBar1.IsIndeterminate = true;
                    GetPageDataInBackground();
                    IsDataLoaded = true;

                }
            }
            catch (Exception ex)
            {
                
                   Exceptions.SaveOrSendExceptions("Exception in UserControl_Loaded method In ShowCast.cs file.", ex);
            }


        }
        #endregion

        #region Events
        private void lbxCast_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {


            try
            {
                if (lbxCast.SelectedIndex == -1)
                    return;

                if (ResourceHelper.AppName == Apps.Video_Games.ToString())
                {
                    if (!AppResources.ShowCastPanoramaPage)
                    {
                        if (!AppResources.ShowCastPanoramaPage)
                        {
                            if (lbxCast.SelectedIndex == -1)
                                return;
                            PageHelper.NavigateTo(NavigationHelper.getVideoGameDescriptionPage((lbxCast.SelectedItem as CastRole).PersonID.ToString(), AppSettings.ShowID, "Cast"));
                            lbxCast.SelectedIndex = -1;

                        }
                    }
                }
                else
                {
                    if (!AppResources.ShowCastPanoramaPage)
                        return;
                }


                if (lbxCast.SelectedIndex == -1)
                    return;
               
                FlurryWP8SDK.Api.LogEvent((lbxCast.SelectedItem as CastRole).PersonName.ToString()+" Gallery Watched");
                AppSettings.PersonID = (lbxCast.SelectedItem as CastRole).PersonID.ToString();
                //AppState.CastPanoramaPageStatus = false;
                PageHelper.NavigateToCastDetailPage(AppResources.CastDetailPageName, AppSettings.PersonID);
                AppSettings.detailtocast++;
                //if (AppSettings.detailtocast > 1)
                //  PageHelper.RemoveEntryFromBackStack(();

               
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in lbxCast_SelectionChanged method In ShowCast.cs file.", ex);
            }
            lbxCast.SelectedIndex = -1;
        }
        #endregion

        #region "Common Methods"
        public void GetPageDataInBackground()
        {

            if (AppResources.ShowCricketDetailPage)
            {


                IDictionary<string, int> index = new Dictionary<string, int>();
               //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
               //var getcastteamid = ((from p in context.MovieCastList where p.ShowID == Convert.ToInt32(AppSettings.ShowID) select p.CategoryID).Distinct()).ToList();
                int showid=int.Parse(AppSettings.ShowID);
                var getcast = Task.Run(async () => await Constants.connection.Table<OnlineVideos.Entities.ShowCast>().Where(i => i.ShowID == showid).ToListAsync()).Result;
                var getcastteamid = getcast.Select(i => i.CategoryID).Distinct().ToList();
                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                Page PageInstance = frame.Content as Page;
                Pivot MainPivot = (Pivot)(PageInstance.FindName("pvtMainDetails"));
                PivotItem TeamAPivot = (PivotItem)(MainPivot.FindName("pvtitmcast1"));
                PivotItem TeamBPivot = (PivotItem)(MainPivot.FindName("pvtitmcast2"));
                ShowCast[] ShowCastArray = new ShowCast[] { (ShowCast)(TeamAPivot.FindName("Cast")), (ShowCast)(TeamBPivot.FindName("Cast1")) };
                TeamAPivot.Header = AppSettings.TeamATitle;

                TeamBPivot.Header = AppSettings.TeamBTitle;
                BackgroundHelper bwHelper = new BackgroundHelper();
               
                for (int i = 0; i < getcastteamid.Count; i++)
                {
                    bwHelper.AddBackgroundTask(
                                                (object s, DoWorkEventArgs a) =>
                                                {

                                                    a.Result = CricketCast.GetCricketCast(AppSettings.ShowID, getcastteamid[(Convert.ToInt32(a.Argument.ToString()))].ToString());
                                                    index.Add(getcastteamid[(Convert.ToInt32(a.Argument.ToString()))].ToString(),Convert.ToInt32(a.Argument.ToString()));
                                                },
                                                (object s, RunWorkerCompletedEventArgs a) =>
                                                {
                                                    int argumentIndex = 0;
                                                    ShowCastList = (List<CastRole>)a.Result;
                                                    index.TryGetValue(ShowCastList.FirstOrDefault().TeamID.ToString(), out argumentIndex);
                                                    if (ShowCastList.Count > 0)
                                                    {
                                                        ((ShowCast)(ShowCastArray[argumentIndex])).lbxCast.ItemsSource = ShowCastList;
                                                        ((ShowCast)(ShowCastArray[argumentIndex])).tblkcast.Visibility = Visibility.Collapsed;


                                                    }
                                                    else
                                                    {
                                                        tblkcast.Text = "No " + AppResources.ShowDetailPageCastPivotTitle as string + " available";
                                                          ((ShowCast)(ShowCastArray[argumentIndex])).tblkcast.Visibility= Visibility.Visible;
                                                    }
                                                    MyProgressBar1.IsIndeterminate = false;
                                                },
                                                (i)
                                              );

                }

                bwHelper.RunBackgroundWorkers();
            }
            else
            {
                BackgroundHelper bwHelper = new BackgroundHelper();

                bwHelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                a.Result = ShowCastManager.GetCastSection(AppSettings.ShowUniqueID.ToString());
                                            },
                                            (object s, RunWorkerCompletedEventArgs a) =>
                                            {
                                                ShowCastList = (List<CastRole>)a.Result;
                                                if (ShowCastList.Count > 0)
                                                {
                                                    lbxCast.ItemsSource = ShowCastList;
                                                    tblkcast.Visibility = Visibility.Collapsed;
                                                }
                                                else
                                                {
                                                    lbxCast.ItemsSource = null;
                                                    tblkcast.Text = "No " + AppResources.FavoritePeoplePivotTitle as string + " available";
                                                    tblkcast.Visibility = Visibility.Visible;
                                                }
                                                MyProgressBar1.IsIndeterminate = false;
                                            }
                                          );

                bwHelper.RunBackgroundWorkers();
            }
           
        }
        private void deletecast_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                MenuItem menu = sender as MenuItem;
                int showid = AppSettings.ShowUniqueID;
                ListBoxItem selectedListBoxItem = lbxCast.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                int personid = Convert.ToInt32((selectedListBoxItem.Content as CastRole).PersonID);
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                OnlineVideos.Entities.ShowCast pid = Task.Run(async () => await Constants.connection.Table<OnlineVideos.Entities.ShowCast>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.PersonID == personid).FirstOrDefaultAsync()).Result;
                int castcount = 0;
                var xqueryw = Task.Run(async () => await Constants.connection.Table<OnlineVideos.Entities.ShowCast>().Where(id => id.PersonID == pid.PersonID).ToListAsync()).Result.GroupBy(id => id.PersonID).OrderByDescending(id => id.Count()).Select(g => new { Count = g.Count() });
                if (xqueryw.Count() > 0)
                {

                    foreach (var itm in xqueryw)
                    {
                        castcount = itm.Count;

                        if (castcount == 1 && Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                        {
                            CastProfile ds1 = Task.Run(async () => await Constants.connection.Table<CastProfile>().Where(i => i.PersonID == personid).FirstOrDefaultAsync()).Result;
                            Task.Run(async () => await Constants.connection.DeleteAsync(ds1));
                        }

                    }
                }

                Task.Run(async () => await Constants.connection.DeleteAsync(pid));

                if (Task.Run(async () => await Storage.FileExists("/" + "Images/PersonImages/" + personid + ".jpg")).Result)
                {
                    Storage.DeleteFile("/" + "Images/PersonImages/" + personid + ".jpg");
                }
                GetPageDataInBackground();
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in deletecast_Click_1 method In ShowCast.cs file.", ex);
            }
        }

        private void ContextMenu_Opened_1(object sender, RoutedEventArgs e)
        {
            try
            {
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                ContextMenu menu = sender as ContextMenu;
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.Status == "Custom").FirstOrDefaultAsync()).Result != null)
                {

                    ListBoxItem selectedListBoxItem = lbxCast.ItemContainerGenerator.ContainerFromItem(menu.DataContext) as ListBoxItem;
                    int personid = Convert.ToInt32((selectedListBoxItem.Content as CastRole).PersonID);

                    OnlineVideos.Entities.ShowCast pid = Task.Run(async () => await Constants.connection.Table<OnlineVideos.Entities.ShowCast>().Where(i => i.ShowID == AppSettings.ShowUniqueID && i.PersonID == personid).FirstOrDefaultAsync()).Result;

                    int castcount = 0;
                    var xqueryw = Task.Run(async () => await Constants.connection.Table<OnlineVideos.Entities.ShowCast>().Where(id => id.PersonID == pid.PersonID).ToListAsync()).Result.GroupBy(id => id.PersonID).OrderByDescending(id => id.Count()).Select(g => new { Count = g.Count() });
                    if (xqueryw.Count() > 0)
                    {

                        foreach (var itm in xqueryw)
                        {
                            castcount = itm.Count;

                            if (castcount == 1)
                            {
                                menu.IsOpen = true;
                            }
                            else
                            {
                                menu.IsOpen = true;
                            }
                        }
                    }
                }
                else
                {
                    menu.IsOpen = false;
                }
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in ContextMenu_Opened_1 method In ShowCast.cs file.", ex);
            }

        }
        #endregion
    }
}
